package com.example.gulimallproduct.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.gulimallproduct.service.CategoryBrandRelationService;
import com.example.gulimallproduct.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimallproduct.dao.CategoryDao;
import com.example.gulimallproduct.entity.CategoryEntity;
import com.example.gulimallproduct.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2.组装成树形结构
        List<CategoryEntity> Menus = categoryEntities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            menu.setChildren(getChildren(menu,categoryEntities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被别的地方引用

        //使用逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        ArrayList<Long> path = new ArrayList<>();
        List<Long> parentPath = findPath(catelogId, path);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     */
    @Transactional
    @Override
    @CacheEvict(value = "category",key = "'Level1Categries'")
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    @Cacheable(value = {"category"},key = "'Level1Categries'")
    @Override
    public List<CategoryEntity> getLevel1Categries() {
        System.out.println("获得category");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        //获取分布式锁:名字一样锁就是一样的
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        try{
            String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
            /**
             * 1.空结果缓存：缓存穿透
             * 2.设置过期时间（随机值）：解决缓存雪崩问题
             * 3.加锁控制并发：解决缓存击穿问题
             */
            if(StringUtils.isEmpty(catalogJSON)){
                //缓存中无数据,查询数据库
                Map<String, List<Catalog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
                String jsonString = JSON.toJSONString(catalogJsonFromDB);
                redisTemplate.opsForValue().set("catalogJSON",jsonString);
                return catalogJsonFromDB;
            }
            Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return result;
        }finally {
            lock.unlock();
        }

    }
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDB() {
        //查出所有的1级分类，获得对应的Id
        List<CategoryEntity> level1Categries = this.getLevel1Categries();
        //封装数据
        Map<String, List<Catalog2Vo>> parent_cid = level1Categries.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询这个一级分类的所有二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catalog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(item -> {
                    //找当前二级分类的三级分类，封装成Vo
                    List<CategoryEntity> category3Entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", item.getCatId()));
                    List<Catalog2Vo.Catalog3Vo> catelog3Vos = null;
                    if(category3Entities!=null){
                        catelog3Vos = category3Entities.stream().map(category3Entity->{
                            Catalog2Vo.Catalog3Vo catelog3Vo = new Catalog2Vo.Catalog3Vo(item.getCatId().toString(),category3Entity.getCatId().toString(),category3Entity.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    Catalog2Vo catelog2Vo = new Catalog2Vo(v.getCatId().toString(), catelog3Vos, item.getCatId().toString(), item.getName());
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<Long> findPath(Long catelogId, ArrayList<Long> path){
        path.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findPath(byId.getParentCid(),path);
        }
        return path;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //1、找到子菜单(递归)
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu, menu2) -> {
            //2、菜单的排序
            return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;

    }

}